import React, { useEffect, Suspense } from 'react'
import {
  BrowserRouter as Router,
  Route,
  Switch
} from 'react-router-dom'
import { useDispatch } from 'react-redux'
import { Empty } from 'antd'
import { setMyInfo } from '@/stores/user'
import routers from './constants/routers'
import './styles/App.scss'

import Header from './components/Header'
import Footer from './components/Footer'

function App() {
  const dispatch = useDispatch()

  /* 自动登录 */
  useEffect(() => {
    autoLogin()
  }, [])

  /**
   * 自动登录
   */
  const autoLogin = async() => {
    if (localStorage.getItem('token')) {
      dispatch(setMyInfo())
    }
  }

  /**
   * 懒加载样式
   */
  const renderLazyLoading = () => (
    <Empty
      description={
        <span>
        页面加载中...
        </span>
      }
    />
  )

  /**
   * 渲染路由
   */
  const renderRouter = () => (
    <Suspense fallback={renderLazyLoading()}>
      <main>
        <Switch>
          {routers.map(router => (
            <Route
              component={router.component}
              exact
              key={router.path}
              path={router.path}
            />
          ))}
        </Switch>
      </main>
    </Suspense>
  )

  return (
    <Router>
      <Header />
      {renderRouter()}
      <Footer />
    </Router>
  )
}

export default App
